<template>
	<view class="cart-page">
		<!-- 顶部全选栏 -->
		<view class="select-all-bar">
			<view class="checkbox" @click="toggleAllSelect">
				<text v-if="isAllSelected">✓</text>
			</view>
			<text class="select-all-text">全选</text>
			<text class="batch-delete" @click="batchDelete" v-if="selectedCount > 0">
				批量删除
			</text>
		</view>

		<view v-for="(goods, index) in cartList" :key="index" class="cart-item">
			<!-- 选择框 -->
			<view class="checkbox" @click="toggleSelect(index)">
				<text v-if="goods.selected">✓</text>
			</view>
			
			<!-- 商品图片 - 添加点击事件 -->
			<image 
				:src="goods.image" 
				class="cart-img" 
				mode="aspectFit" 
				@click="goToCheckoutWithGoods(goods)"
			/>

			<!-- 商品信息 - 添加点击事件 -->
			<view class="cart-info" @click="goToCheckoutWithGoods(goods)">
				<view class="cart-name">{{ goods.name }}</view>
				<!-- 新增规格显示 -->
				  <view class="cart-spec" v-if="goods.specGroups || goods.specText">
				    {{ getCartGoodsSpec(goods) }}
				  </view>
				<view class="cart-price">￥{{ goods.price }}束</view>

				<!-- 数量控制 -->
				<view class="quantity-control">
					<text class="btn minus" @click.stop="changeQuantity(index, -1)">-</text>
					<text class="quantity">{{ goods.count }}</text>
					<text class="btn plus" @click.stop="changeQuantity(index, 1)">+</text>
				</view>
			</view>

			<view class="delete-btn" @click="deleteGoods(index)">
				<text>删除</text>
			</view>
		</view>

		<!-- 空购物车提示 -->
		<view class="empty-cart" v-if="!cartList.length">购物车暂无商品</view>

		<!-- 底部价格计算栏 -->
		<view class="bottom-nav" v-if="cartList.length">
			<view class="selected-info">
				<text>已选 {{ selectedCount }} 件</text>
			</view>
			<view class="total-price">
				合计: <text class="price">¥{{ totalPrice }}</text>
			</view>
			<!-- 结算按钮 - 只有选中商品时可点击 -->
			<view 
				class="settle-btn" 
				@click="goToCheckout"
				:class="{ disabled: selectedCount === 0 }"
				:disabled="selectedCount === 0"
			>
				结算
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				cartList: [], // 购物车数据
			};
		},
		computed: {
			// 计算选中商品的总价
			totalPrice() {
				let total = 0;
				this.cartList.forEach(goods => {
					if (goods.selected) { // 只计算选中的商品
						// 确保 price 是字符串
						const priceStr = String(goods.price);
						// 提取价格数字（处理类似"¥ 35/袋"这种格式）
						const priceNum = parseFloat(priceStr.replace(/[^\d.]/g, ''));
						total += priceNum * goods.count;
					}
				});
				return total.toFixed(2);
			},
			// 是否全选
			isAllSelected() {
				if (this.cartList.length === 0) return false;
				return this.cartList.every(goods => goods.selected);
			},
			// 选中商品数量
			selectedCount() {
				return this.cartList.filter(goods => goods.selected).length;
			}
		},
		onShow() {
			// 页面显示时，从本地读取购物车数据
			this.cartList = uni.getStorageSync('cartList') || [];
			// 初始化商品属性
			this.cartList.forEach(goods => {
				if (!goods.count) goods.count = 1;
				if (goods.selected === undefined) goods.selected = false; // 初始化选择状态
				goods.price = String(goods.price);
			});
			this.updateCartStorage();
		},
		methods: {
			// 切换单个商品选择状态
			toggleSelect(index) {
				this.cartList[index].selected = !this.cartList[index].selected;
				this.updateCartStorage();
			},
			
			// 全选/取消全选
			toggleAllSelect() {
				const isAllSelected = this.isAllSelected;
				this.cartList.forEach(goods => {
					goods.selected = !isAllSelected;
				});
				this.updateCartStorage();
			},
			
			// 批量删除选中商品
			batchDelete() {
				if (this.selectedCount === 0) return;
				
				uni.showModal({
					title: '提示',
					content: `确定要删除选中的 ${this.selectedCount} 件商品吗？`,
					success: (res) => {
						if (res.confirm) {
							// 保留未选中的商品
							this.cartList = this.cartList.filter(goods => !goods.selected);
							this.updateCartStorage();
						}
					}
				});
			},

			// 改变商品数量
			changeQuantity(index, num) {
				const newCount = this.cartList[index].count + num;
				// 数量不能小于1
				if (newCount < 1) return;

				this.cartList[index].count = newCount;
				// 更新本地存储
				this.updateCartStorage();
			},

			// 单个删除商品
			deleteGoods(index) {
				uni.showModal({
					title: '提示',
					content: '确定要删除该商品吗？',
					success: (res) => {
						if (res.confirm) {
							this.cartList.splice(index, 1);
							// 更新本地存储
							this.updateCartStorage();
						}
					}
				});
			},

			// 更新本地存储的购物车数据
			updateCartStorage() {
				uni.setStorageSync('cartList', this.cartList);
			},

			// 跳转至商品结算页面（只传递选中的商品）
			goToCheckout() {
			  if (this.selectedCount === 0) return;
			  
			  // 筛选并转换选中商品格式，与立即购买保持一致
			  const selectedGoods = this.cartList
			    .filter(goods => goods.selected)
			    .map(goods => this.formatGoodsData(goods));
			  
			  // 编码并跳转结算页
			  const cartData = encodeURIComponent(JSON.stringify(selectedGoods));
			  uni.navigateTo({
			    url: "/pages/goodsDetail/checkout?cartData=" + cartData
			  });
			},
			
			// 点击单个商品跳转到结算页面
			goToCheckoutWithGoods(goods) {
				// 格式化单个商品数据
				const goodsData = [this.formatGoodsData(goods)];
				
				// 编码并跳转结算页
				const cartData = encodeURIComponent(JSON.stringify(goodsData));
				uni.navigateTo({
				  url: "/pages/goodsDetail/checkout?cartData=" + cartData
				});
			},
			
			// 格式化商品数据（提取公共逻辑）
			formatGoodsData(goods) {
				return {
					id: goods.id,
					name: goods.name,
					imageUrl: goods.image,
					price: parseFloat(goods.price) || 0,
					quantity: goods.count,
					spec: this.getCartGoodsSpec(goods)
				};
			},
			
			// 补充购物车商品的规格文本获取方法
			getCartGoodsSpec(goods) {
			  // 优先使用已保存的规格文本
			  if (goods.specText) {
			    return goods.specText;
			  }
			  // 否则通过规格组计算
			  if (goods.specGroups) {
			    return goods.specGroups.map(group => {
			      const option = group.options.find(item => item.value === group.selectedValue);
			      return `${group.name}: ${option ? option.label : '无'}`;
			    }).join(', ');
			  }
			  // 若无规格信息
			  return '无规格';
			}
		}
	};
</script>

<style scoped>
	/* 原有样式保持不变 */
	.cart-page {
		padding: 15px;
		min-height: 90vh;
		box-sizing: border-box;
		padding-bottom: 80px;
		position: relative;
	}

	/* 全选栏样式 */
	.select-all-bar {
		display: flex;
		align-items: center;
		padding: 10px 0;
		margin-bottom: 10px;
		border-bottom: 1px solid #eee;
	}
	
	.checkbox {
		width: 24px;
		height: 24px;
		border: 1px solid #ddd;
		border-radius: 4px;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 10px;
		color: #ff5722;
		font-weight: bold;
	}
	
	.select-all-text {
		font-size: 16px;
		color: #333;
	}
	
	.batch-delete {
		margin-left: auto;
		color: #ff4d4f;
		font-size: 14px;
		padding: 5px 10px;
		border: 1px solid #ff4d4f;
		border-radius: 4px;
	}

	.cart-item {
		display: flex;
		align-items: center;
		margin-bottom: 15px;
		border-bottom: 1px solid #eee;
		padding-bottom: 10px;
	}

	.cart-img {
		width: 80px;
		height: 80px;
		margin-right: 10px;
		border-radius: 8px;
	}

	.cart-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.cart-name {
		font-weight: bold;
		margin-bottom: 8px;
		font-size: 16px;
	}
	
	.cart-spec {
	  font-size: 12px;
	  color: #666;
	  margin-bottom: 4px;
	}

	.cart-price {
		color: #ff5722;
		margin-bottom: 8px;
		font-size: 15px;
	}

	/* 数量控制样式 */
	.quantity-control {
		display: flex;
		align-items: center;
		width: 120px;
	}

	.quantity-control .btn {
		width: 30px;
		height: 30px;
		display: flex;
		align-items: center;
		justify-content: center;
		border: 1px solid #ddd;
		border-radius: 4px;
		background-color: #f5f5f5;
	}

	.quantity-control .minus {
		color: #666;
	}

	.quantity-control .plus {
		color: #ff5722;
	}

	.quantity-control .quantity {
		width: 40px;
		text-align: center;
		margin: 0 10px;
	}

	/* 删除按钮样式 */
	.delete-btn {
		color: #ff4d4f;
		font-size: 14px;
		padding: 5px 10px;
		border: 1px solid #ff4d4f;
		border-radius: 4px;
		margin-left: 10px;
	}

	.empty-cart {
		text-align: center;
		color: #999;
		padding: 20px;
		margin-top: 50px;
	}

	/* 底部价格栏样式 */
	.bottom-nav {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px;
		background-color: #fff;
		border-top: 1px solid #eee;
		position: fixed;
		bottom: 50px;
		left: 0;
		right: 0;
		height: 40px;
	}
	
	.selected-info {
		font-size: 14px;
		color: #666;
		margin-right: 10px;
	}

	.total-price {
		font-size: 16px;
		flex: 1;
	}

	.total-price .price {
		color: #ff5722;
		font-weight: bold;
		font-size: 18px;
	}

	.settle-btn {
		background-color: #ff5722;
		color: #fff;
		padding: 8px 24px;
		border-radius: 4px;
		font-weight: bold;
		margin-left: 10px;
	}
	
	.settle-btn.disabled {
		background-color: #ccc;
		cursor: not-allowed;
	}
</style>